var app = getApp();
const utils = require('../../utils/util.js');

Page({
  data: {
    animationData: "",
    showModalStatus: false,
    cardInfo: {},
    loadingMoreHidden: true,
    animationData2: "",
    showModalStatus2: false,
    tagId: null,
    staffid: null,
    animationData3: "",
    showModalStatus3: false,
    ishowLike: false,
    isSign: false,
    sourceId: 1,
    supportCompany: "",
    supportPhone: "",
    msgLength: 0,
    animationData4: "",
    showModalStatus4: false,
    showModalStatus5: false,
    animationData5: "",
    mobile: "",
    pathGoods: "",
    showTabBar: true,
    shareTitle: "",
    isAccredit: false, //是否授权
    query: ''
  },

  //查看名片列表
  formSubmitCardList: function (e) {
    var formId = e.detail.formId;
    utils.addFormIdMsg(formId);
    wx.redirectTo({
      url: '/pages/weijieke/cardList/index'
    })
  },

  //转发
  formSubmitCardShare: function (e) {
    var formId = e.detail.formId;
    utils.addFormIdMsg(formId);
    this.showModal();
  },

  /*
  * source = 1 扫码
  * source = 2 转发
  */
  onLoad: function (e) {
    let that = this;
    let params = decodeURIComponent(e.scene);
    console.log(e);
    console.log('小程序码携带的参数', params);
    if (params && params != 'undefined') {//扫描小程序二维码进入
      let type = 1;//路由
      let param = '';//参数
      let plist = '';
      if (params.indexOf('p-') != -1) {
        type = params.match(/t-(\S*)\*p/)[1];//路由
        param = params.match(/p-(\S*)/)[1];//参数
        plist = param.toString().split('_');
      } else {
        type = params.match(/t=(\S*)&p/)[1];//路由
        param = params.match(/p=(\S*)/)[1];//参数
        plist = param.toString().split('#');
      }
      if (type == 10) {//分销二维码
        if (plist[0]) {
          wx.setStorageSync("cardId", plist[0]);
        }
        if (plist[2]) {
          wx.setStorageSync("disid", plist[2]);
        }
        if (plist[3]) {
          wx.setStorageSync("agentid", plist[3]);
        }
      }
    } else {
      if (e.agentId) {
        wx.setStorageSync("agentid", e.agentId);
      }
      if (e.disId) {
        wx.setStorageSync("disid", e.disId);
      }
      if (e.id) {
        wx.setStorageSync("cardId", e.id)
      }
      if (e.source) {
        that.setData({ sourceId: e.source })
      }
    }
    that.getShareTip();

    if (e.isFriendState) {
      that.getAiCardInfo();
      that.GetVideoInfo();
    }
  },

  // 获取名片信息
  getAiCardInfo: function () {
    var that = this;
    var cardId = wx.getStorageSync("cardId");
    let uid = app.globalData.friendUid;
    if (app.globalData.userInfo) {
      uid = app.globalData.userInfo.Uid;
    }
    if (cardId) {
      wx.request({
        url: app.globalData.host + '/api/BusinessCard/GetAiCardDetail?uid=' + uid + '&staffId=' + cardId,
        success: function (res) {
          that.setData({
            loadingMoreHidden: false
          })
          if (res.data.Code == 0) {
            var cardInfo = res.data.Data;
            if (cardInfo.DisplayState != 1) {
              wx.showModal({
                title: '提示',
                content: '该名片已失效！',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    wx.redirectTo({
                      url: '/pages/weijieke/cardList/index',
                    })
                  }
                }
              })
            } else {
              cardInfo = that.cartSplitList(cardInfo);
              that.setData({
                cardInfo: cardInfo
              })
              that.getMsgUnRead(cardInfo.CardInfo.Uid)
              utils.aiCardActionRecord(4);
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/weijieke/cardList/index',
                  })
                }
              }
            })
          }
        }
      })
    } else {
      that.setData({
        loadingMoreHidden: false
      })
      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {// 已授权
            wx.redirectTo({
              url: '/pages/weijieke/cardList/index',
            })
          }
        }
      })
    }
  },

  //名片信息字符串数组处理
  cartSplitList: function (cardInfo) {
    var tagList = cardInfo.TagList;
    if (tagList.length > 0 && tagList != null) {
      for (var i = 0; i < tagList.length; i++) {
        tagList[i].TagName = tagList[i].TagName.substr(0, 25);
      }
    }
    var urlImg = "https://static.711688.net.cn/upload/card/source/thumb600_600/"
    var clientimgs = cardInfo.clientimgs;
    if (clientimgs) {
      if (clientimgs.length > 0 && clientimgs != null) {
        for (var k = 0; k < clientimgs.length; k++) {
          clientimgs[k] = utils.formatAvater(clientimgs[k], urlImg);
        }
      }
    }
    cardInfo.CardInfo.Avater = utils.formatAvater(cardInfo.CardInfo.Avater, "https://static.711688.net.cn/upload/card/source/");
    var imgs = cardInfo.CardInfo.Imgs;
    var imgList = [];
    if (imgs) {
      imgs = imgs.split(",");
      for (let i = 0; i < imgs.length; i++) {
        imgList.push(utils.formatAvater(imgs[i], "https://static.711688.net.cn/upload/card/source/"));
      }
      cardInfo.imgList = imgList;
    }
    return cardInfo
  },

  //修改客户来源
  updateSource: function (source) {
    var cardId = wx.getStorageSync("cardId")
    let uid = app.globalData.userInfo.Uid;
    // if(!uid){
    //   uid = app.globalData.friendUid;
    // }
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/UpdateSource?staffId=' + cardId + '&uid=' + uid + '&source=' + source,
      success: function (res) {

      },
    })
  },

  /**
   * 获取底部信息
   */
  GetVideoInfo: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/GetInfo?id=' + app.globalData.storeId,
      success: function (res) {
        if (res.data.Code == 0) {
          that.data.supportPhone = res.data.Data.SupportPhone;
          that.setData({
            supportCompany: res.data.Data.SupportCompany,
          })
        }
      }
    })
  },

  //获取未读消息
  getMsgUnRead: function (stuffUId) {
    var that = this;
    let uid = app.globalData.friendUid;
    if (app.globalData.userInfo) {
      uid = app.globalData.userInfo.Uid;
    }
    wx.request({
      url: app.globalData.host + '/api/WebIM/GetUnRead?uid=' + uid + "&stuffUId=" + stuffUId,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            msgLength: res.data.Data
          })
        }
      },
    })
  },

  //进入聊天页面
  formSubmit: function (e) {
    var cardInfo = this.data.cardInfo.CardInfo;
    var mobile = wx.getStorageSync("mobile");
    if (mobile) {
      // wx.navigateTo({
      //   url: '/pages/weijieke/Business/Business?seltoid=' + cardInfo.Uid + '&name=' + cardInfo.Name
      // })
      console.log('聊天');
      utils.toChat(cardInfo);
    }
    // var formId = e.detail.formId;
    // utils.addFormIdMsg(formId);
    // utils.aiCardActionRecord(18);
  },

  //获取手机号
  getPhoneNumber: function (e) {
    let that = this;
    var cardInfo = that.data.cardInfo.CardInfo;
    let isAccredit = that.data.isAccredit;
    utils.getMobile(e);
    if (isAccredit) {
      console.log('聊天');
      utils.toChat(cardInfo);
      // wx.navigateTo({
      //   url: '/pages/weijieke/Business/Business?seltoid=' + cardInfo.Uid + '&name=' + cardInfo.Name
      // })
    }
  },

  //是否授权登陆
  toShowToast: function () {
    let back = '/pages/index/index';
    wx.navigateTo({
      url: '../accredit/index?back=' + back,
    })
  },

  //拨打服务商电话
  callCompany: function () {
    var that = this;
    if (that.data.supportPhone == '') {
      return
    } else {
      wx.makePhoneCall({
        phoneNumber: that.data.supportPhone
      })
    }
  },

  //复制文本
  copyDataInfo: function (e) {
    let data = e.currentTarget.dataset.copy;
    let wxid = e.currentTarget.dataset.wxid;
    wx.setClipboardData({
      data: data,
      success: function (res) {
        if (wxid == 1) {//复制微信
          utils.aiCardActionRecord(3);
        }
        if (wxid == 2) {//邮箱
          utils.aiCardActionRecord(12);
        }
      }
    })
  },

  //拨打电话
  makeCallPhone: function (e) {
    let mobile = e.currentTarget.dataset.mobile;
    let phone = e.currentTarget.dataset.phone;
    if (phone) {
      wx.makePhoneCall({ phoneNumber: phone })
      utils.aiCardActionRecord(16);
    }
    if (mobile) {
      wx.makePhoneCall({ phoneNumber: mobile })
      utils.aiCardActionRecord(9);
    }
  },

  //添加到通讯录
  addPhonePerson: function () {
    var that = this;
    var cardInfo = that.data.cardInfo.CardInfo;
    wx.addPhoneContact({
      firstName: cardInfo.Name, //名字
      mobilePhoneNumber: cardInfo.Mobile, //手机号
      organization: cardInfo.Company, //公司
      title: cardInfo.Position, //职位
      email: cardInfo.Email,
      workAddressStreet: cardInfo.Address, //工作详细地址
      success: function (res) {
        utils.aiCardActionRecord(7)
      }
    })
  },

  toPoste: function () {
    var cardInfo = JSON.stringify(this.data.cardInfo)
    wx.navigateTo({
      url: '/pages/weijieke/sharePoste/index?cardinfo=' + this.encodeUnicode(cardInfo)
    })
  },

  // 转为unicode 编码
  encodeUnicode: function (str) {
    var res = [];
    for (var i = 0; i < str.length; i++) {
      res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
    }
    return "\\u" + res.join("\\u");
  },


  //图片预览
  prewCardImg: function (e) {
    let imgList = this.data.cardInfo.imgList;
    let src = e.currentTarget.dataset.currsrc;
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
  },

  onReady: function (e) {

  },

  // 底部弹出层
  showModal: function () {
    // 显示遮罩层
    this.setData({ showTabBar: false });
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    // 隐藏遮罩层
    this.setData({ showTabBar: true });
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  // 信息弹出框
  showModalInfo: function () {
    if (this.data.showModalStatus4) {
      this.hideModalInfo();
    } else {
      this.setData({
        showModalStatus4: true
      })
    }
  },
  hideModalInfo: function () {
    this.setData({
      showModalStatus4: false
    })
  },
  // 标签加1
  showModalAdd: function (e) {
    let tagId = e.currentTarget.dataset.tagid;
    if (this.data.tagId != tagId || this.data.tagId == null) {
      var animation = wx.createAnimation({
        duration: 500,
        timingFunction: "linear",
        delay: 0
      })
      this.animation = animation
      animation.scale(0, 0).translateY(0).step()
      this.setData({
        animationData2: animation.export(),
        showModalStatus2: true,
        tagId: tagId
      })
      setTimeout(function () {
        animation.scale(2, 2).translateY(-5).step()
        this.setData({
          animationData2: animation.export(),
        })
      }.bind(this), 200)
      var that = this;
      setTimeout(function () {
        that.setData({
          showModalStatus2: false
        })
      }, 1000)
      this.addTagUp(tagId)
    }
  },

  //标签点赞
  addTagUp: function (tagid) {
    var that = this;
    var cardId = wx.getStorageSync("cardId")
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/AddTagUp?uid=' + app.globalData.userInfo.Uid + '&tagId=' + tagid + '&staffId=' + cardId,
      success: function (res) {
        if (res.data.Code == 0) {

        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false,
          })
        }
      },
    })
  },

  //名片点赞
  addCardUp: function (staffid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/AddCardUp?uid=' + app.globalData.userInfo.Uid + '&staffId=' + staffid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            staffid: staffid
          })
          that.getAiCardInfo();
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false,
          })
        }
      },
    })
  },

  // 名片点赞
  showAddCardUp: function (e) {
    let staffid = e.currentTarget.dataset.staffid;
    if (this.data.staffid == null) {
      var animation = wx.createAnimation({
        duration: 1000,
        timingFunction: "linear",
        delay: 0
      })
      this.animation = animation
      animation.scale(1, 1).translateY(0).step();
      this.setData({
        animationData5: animation.export(),
        showModalStatus5: true,
        ishowLike: true
      })
      setTimeout(function () {
        animation.scale(2, 2).translateY(-30).step();
        this.setData({
          animationData5: animation.export(),
        })
      }.bind(this), 200)
      var that = this;
      setTimeout(function () {
        that.setData({
          showModalStatus5: false,
          ishowLike: true
        })
        that.addCardUp(staffid)
      }, 1000)
    }
  },

  //个性签名点赞
  addSignUp: function () {
    var that = this;
    if (!that.data.isSign) {
      var cardId = wx.getStorageSync("cardId")
      wx.request({
        url: app.globalData.host + '/api/BusinessCard/AddSignUp?uid=' + app.globalData.userInfo.Uid + '&staffId=' + cardId,
        success: function (res) {
          if (res.data.Code == 0) {
            that.setData({
              isSign: res.data.Data
            })
            that.getAiCardInfo();
          }
        },
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var userInfo = app.globalData.userInfo;
    that.hideModal();
    if (userInfo) {
      console.log("用户信息存在");
      that.getAiCardInfo();
      that.updateSource(that.data.sourceId);
      that.GetVideoInfo();
      that.GetSharePagePath();
      that.onMyEvent(userInfo.Uid);
      utils.isAccredit(function (isAccredit) {
        that.setData({
          isAccredit: isAccredit
        })
      });
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
    var mobile = wx.getStorageSync("mobile");
    if (mobile) {
      this.setData({ mobile: mobile })
    }
  },
  // 连接socket监听聊天消息
  onMyEvent: function (uid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            let fromuid = res.data.Data.Id;
            console.log('开始建立连接');
            wx.connectSocket({
              url: app.globalData.socketUrl,
              success: function (res) {
                console.log('创建一个 WebSocket 连接', res);
              },
              fail: function (err) {
                console.log('创建一个 WebSocket 连接失败', err);
              }
            })
            // 监听连接成功
            wx.onSocketOpen(function () {
              console.log('socket连接成功者', fromuid);
              let datas = { "type": "connect", "from_uid": fromuid };
              wx.sendSocketMessage({
                data: JSON.stringify(datas),
                success: function (res) {
                  console.log('发送成功', res);
                }, fail: function (err) {
                  console.log('发送失败', err);
                }
              })
            })
            // 监听 WebSocket 接受到服务器的消息
            wx.onSocketMessage(message => {
              console.log('监听 WebSocket 接受到服务器的消息事件=================', message);
              //把JSONStr转为JSON
              message = message.data.replace(" ", "");
              if (typeof message != 'object') {
                message = message.replace(/\ufeff/g, ""); //重点
                var jj = JSON.parse(message);
                message = jj;
                if (message.type == 'send' && message.content) {
                  let msgLength = that.data.msgLength;
                  wx.request({
                    url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + that.data.cardInfo.CardInfo.Uid,
                    success: function (res) {
                      if (res.data.Code == 0 && res.data.Data) {
                        let fromuid = res.data.Data.Id;
                        if (message.from_uid == fromuid) {
                          that.setData({
                            msgLength: msgLength + 1
                          })
                        }
                      }
                    }
                  })
                }
              }
              console.log("【websocket监听到消息】内容如下：", message);
            })
            wx.onSocketError(function (err) {
              console.log('监听 WebSocket 错误事件', err);
            });
            wx.onSocketClose(function (res) {
              console.log('WebSocket 已关闭啦啦啦！', res)
            });
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  //获取分销商信息
  GetSharePagePath: function () {
    var that = this;
    var disId = wx.getStorageSync('disid');
    var agentId = wx.getStorageSync('agentid');
    var cardId = wx.getStorageSync("cardId");
    if (!disId) {
      disId = 0
    }
    if (!agentId) {
      agentId = 0
    }
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetDistributorAndCreate',
      data: {
        userId: app.globalData.userInfo.Uid,
        storeId: app.globalData.storeId,
        disId: disId,
        agentId: agentId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var path = '';
          let query = '';
          let disId = 0;
          let agentId = 0;
          if (res.data.Data.IsAgent == 0) {
            disId = res.data.Data.Id;
            agentId = res.data.Data.AgentDId;
            path = "/pages/index/index?disId=" + disId + "&agentId=" + agentId + "&id=" + cardId + "&source=2"
          } else {
            agentId = res.data.Data.Id;
            path = "/pages/index/index?disId=" + disId + "&agentId=" + agentId + "&id=" + cardId + "&source=2"
          }
          query = 'id=' + cardId + '&uid=' + app.globalData.userInfo.Uid + '&disId=' + disId + '&agentId=' + agentId + '&isFriendState=1';
          that.data.pathGoods = path;
          that.data.query = query;
        }
      }
    })
  },

  //获取分享语
  getShareTip() {
    var that = this;
    var cardId = wx.getStorageSync("cardId");
    wx.request({
      url: app.globalData.host + '/api/staff/GetShareTip?staffId=' + cardId,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Value) {
            that.data.shareTitle = res.data.Data.Value;
          }
        }
      },
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    var cardInfo = that.data.cardInfo;
    var shareTitle = "";
    if (that.data.shareTitle) {
      shareTitle = that.data.shareTitle
    } else {
      shareTitle = "你好，我是" + cardInfo.CardInfo.Company + "的" + cardInfo.CardInfo.Name
    }
    utils.aiCardActionRecord(2);
    return {
      title: shareTitle,
      imageUrl: cardInfo.CardInfo.Avater,
      path: this.data.pathGoods,
      success: function (res) {
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
        that.hideModal();
      }
    }
  },

  //分享朋友圈
  onShareTimeline: function () {
    let that = this;
    let cardInfo = that.data.cardInfo;
    let imageUrl = cardInfo.CardInfo.Avater;
    let query = that.data.query;
    if (!query) {
      let uid = app.globalData.friendUid
      if (app.globalData.userInfo) {
        uid = app.globalData.userInfo.Uid
      }
      query = 'id=' + cardInfo.CardInfo.Id + '&uid=' + uid + '&isFriendState=1';
    }
    var shareTitle = "";
    if (that.data.shareTitle) {
      shareTitle = that.data.shareTitle
    } else {
      shareTitle = "你好，我是" + cardInfo.CardInfo.Company + "的" + cardInfo.CardInfo.Name
    }
    return {
      title: shareTitle,
      query: query,
      imageUrl: imageUrl
    }
  },

  //离开当前页面
  onUnload: function () {
    utils.toCloseSocket();
  },
  onHide: function () {
    utils.toCloseSocket();
  }
})